﻿namespace asyncCancellationToken
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            // 1
            //CancellationTokenSource cts = new CancellationTokenSource();
            //cts.CancelAfter(TimeSpan.FromSeconds(2));//5秒后取消
            //await DownLoadAsync("https://www.baidu.com", 100, cts.Token);

            //// 手动触发取消
            //cts.Cancel();

            // 2
            await TaskWhenAll();
            Console.WriteLine("Hello, World!");
        }

        static async Task DownLoadAsync(string url, int n, CancellationToken cancellationToken)
        {
            using (var client = new HttpClient())
            {
                for (int i = 0; i < n; i++) 
                {
                    string html = await client.GetStringAsync(url);
                    Console.WriteLine(html);

                    // 手动判断取消,已经执行完读取数据
                    if (cancellationToken.IsCancellationRequested)
                    {
                        Console.WriteLine("Cancellation Requested");
                        return;
                    }

                    // 抛异常取消
                    //cancellationToken.ThrowIfCancellationRequested();
                }
            }



        }
        static async Task DownLoadAsync2(string url, int n, CancellationToken cancellationToken)
        {
            using (var client = new HttpClient())
            {
                for (int i = 0; i < n; i++)
                {
                    var resp = await client.GetAsync(url, cancellationToken);

                    // 请求内部超时，自己判断是否抛异常
                    string html = await resp.Content.ReadAsStringAsync();

                    Console.WriteLine(html);
                }
            }
        }

        static async Task TaskWhenAll()
        {
            // 创建一些模拟的异步任务  
            Task<int> task1 = Task.Run(async () =>
            {
                await Task.Delay(1000); // 模拟异步操作，延迟1秒  
                return 1;
            });

            Task<int> task2 = Task.Run(async () =>
            {
                await Task.Delay(2000); // 模拟异步操作，延迟2秒  
                return 2;
            });

            Task<int> task3 = Task.Run(async () =>
            {
                await Task.Delay(3000); // 模拟异步操作，延迟3秒  
                return 3;
            });

            // 使用Task.WhenAll等待所有任务完成  
            Task<int[]> whenAllTask = Task.WhenAll(task1, task2, task3);

            // 等待所有任务完成，并获取结果  
            int[] results = await whenAllTask;

            // 输出结果  
            Console.WriteLine("所有任务都已完成。");
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }
        }

    }
}
